package club.kynb.mall.application.flow.user;

import club.kynb.mall.application.context.AuthenticationContext;
import club.kynb.mall.application.model.model.command.AuthenticationCommand;
import club.kynb.mall.user.api.IUserService;
import club.kynb.mall.user.constant.UserStatus;
import club.kynb.mall.user.constant.UserType;
import club.kynb.mall.user.model.dto.UserDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author kynb_club@163.com
 * @since 2020/12/18 1:48 下午
 * 检查成员已经存在过滤器
 */
@Slf4j
@Component
@AllArgsConstructor
public class CheckUserAlreadyExistFilter implements Filter<AuthenticationContext> {
    private final IUserService iUserService;

    @Override
    public void doFilter(AuthenticationContext authenticationContext, FilterInvoker<AuthenticationContext> filterInvoker) {
        log.info("检查成员已经存在过滤器 start");
        AuthenticationCommand authenticationCommand = authenticationContext.getAuthenticationCommand();
        final Optional<UserDTO> userOptional = iUserService.getUserByPhone(authenticationCommand.getPhone(), UserType.CUSTOMER.name());
        if (userOptional.isPresent()) {
            UserDTO userDTO = userOptional.get();
            if (userDTO.getStatus().equals(UserStatus.NORMAL.code())
                    ||
                    userDTO.getStatus().equals(UserStatus.FREEZE.code())
            ) {
                throw Errors.BIZ.exception("用户已经注册过了");
            }
        }
        log.info("检查成员已经存在过滤器 end");
        filterInvoker.invoke(authenticationContext);
    }
}
